package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.dao.PermissionDao;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        if (queryString != null && queryString.contains(" ")) {
            queryString = queryString.replaceAll(" ", "");
        }
        Page<Permission> list = permissionDao.findByPage(queryString);
        long total = list.getTotal();
        return new PageResult(total, list);
    }

    @Override
    public Result add(Permission permission) {
        try {
            permissionDao.add(permission);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }
    }

    @Override
    public Result edit(Permission permission) {
        try {
            permissionDao.edit(permission);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    @Override
    public Result findByID(Integer id) {
        try {
            Permission permission = permissionDao.findById(id);
            return new Result(true, "成功", permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "失败");
        }
    }

    @Override
    public Result delete(Integer id) {
        try {
            long count = permissionDao.findInRole(id);
            if (count > 0) {
                return new Result(false, "此权限正在使用,无法删除");
            }
            permissionDao.delete(id);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

    /**
     * 查询所有的权限信息回显
     * @return
     */
    @Override
    public List<Permission> findAllPerm() {
       return permissionDao.findAll();
    }
}
